package com.pmcc.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 字符串常用工具类
 * Created by Admin on 2016/1/28.
 */
public class StringUtil {

    public static final String SQL = "sql"; // sql语句
    public static final String PARAMETERS = "parameters"; // 参数
    public static final String COLUMN = "column"; // 字段
    public static final String VALUE = "value"; // 值
    public static final String PROPERTY = "property"; // 排序字段
    public static final String DIRECTION = "direction"; // 排序方式
    public static final String ASC = "asc"; // 正序
    public static final String DESC = "desc"; // 倒序

    public static  final char ATYPEFLAG='{';
    public static  final char BTYPEFLAG='}';

    public static void main(String[] args) throws UnsupportedEncodingException {

        String s="sc_gt2_A";
        String varcode=s.substring(0,s.length()-2);
        String businessType=s.substring(s.length()-1,s.length());
        System.out.println(varcode);
        System.out.println(businessType);
    }



    public static List<String> getCode(String body) {
        char[] c=body.toCharArray();
        List<String> b=new ArrayList<>();
        Boolean flag=false;
        String str="";
        for(int i=0;i<c.length;i++){
            if(c[i]==BTYPEFLAG){
                flag=false;
                b.add(str);
                str="";
            }
            if(flag){
                str=str+c[i];
            }
            if(c[i]==ATYPEFLAG){
               flag=true;
            }

        }

    return b;
    }

    public static List<String> readFile(String path) {

        List<String> dataList = new ArrayList<String>();
        BufferedReader br = null;
        try {

            File file = new File(path);
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));
            String line = "";
            while ((line = br.readLine()) != null) {
                dataList.add(line);
//                System.out.println(line);
            }
        } catch (Exception e) {
        } finally {
            if (br != null) {
                try {
                    br.close();
                    br = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return dataList;
    }

    /**
     * String转map
     *
     * @param inStr
     * @param splitstr
     * @param elesplitstr
     * @return
     */
    public static List toMapValues(String inStr, String splitstr,
                                   String elesplitstr) {
        ArrayList resultlist = new ArrayList();
        if (inStr == null || inStr.equals("")) {
            return null;
        }
        if (inStr.indexOf(splitstr) == -1) {
            return null;
        }
        StringTokenizer str = new StringTokenizer(inStr.trim(), splitstr);
        while (str.hasMoreTokens()) {
            String tmpstr = str.nextToken();
            int i = tmpstr.indexOf(elesplitstr);
            if (i != -1) {
                HashMap map = new HashMap();
                map.put(tmpstr.substring(0, i), tmpstr.substring(i + 1));
                resultlist.add(map);
            }
        }
        return resultlist;
    }

    /**
     * 字符串转 List<String>
     *
     * @param inStr
     * @param splitstr
     * @return
     */
    public static ArrayList<String> toList(String inStr, String splitstr) {

        ArrayList<String> resulist = new ArrayList<String>();
        if (inStr == null || inStr.equals("")) {
            return resulist;
        }
        if (inStr.indexOf(splitstr) == -1) {
            resulist.add(inStr);
            return resulist;
        }
        StringTokenizer str = new StringTokenizer(inStr.trim(), splitstr);
        while (str.hasMoreTokens()) {
            resulist.add(str.nextToken());
        }
        return resulist;
    }

    /**
     * 字符串转 List<Int>
     *
     * @param inStr
     * @param splitstr
     * @return
     */
    public static ArrayList toIntList(String inStr, String splitstr) {
        ArrayList resulist = new ArrayList();
        if (inStr == null || inStr.equals("")) {
            return resulist;
        }
        if (inStr.indexOf(splitstr) == -1) {
            if (isInteger(inStr)) {
                resulist.add(Integer.valueOf(inStr));
            }
            return resulist;
        }
        String strs[] = inStr.split(splitstr);
        for (String str : strs) {
            if (isInteger(str)) {
                resulist.add(Integer.valueOf(str));
            }
        }
        return resulist;
    }

    public static boolean isInteger(String str) {
        try {
            Integer.valueOf(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 判断字符串是否为数字
     *
     * @param str
     * @return
     */
    public static boolean isNumber(String str) {
        for (int t = 0; t < str.length(); t++) {
            if (!Character.isDigit(str.charAt(t))) {
                return false;
            }
        }
        return true;
    }


    public static Calendar toDate(String qktdatestart) {
        Calendar calendar = Calendar.getInstance();
        String tmpkey = qktdatestart;

        int y = 0, m = 1, d = 1;
        if (tmpkey != null) {
            StringTokenizer st = new StringTokenizer(tmpkey, "-");
            if (st.hasMoreTokens()) {
                y = Integer.parseInt(st.nextToken());
            }
            if (st.hasMoreTokens()) {
                m = Integer.parseInt(st.nextToken()) - 1;
            }
            if (st.hasMoreTokens()) {
                d = Integer.parseInt(st.nextToken());
            }
            calendar.set(y, m, d, 0, 0, 0);

        }
        return calendar;
    }

    /**
     * Get float parameter from request. If specified parameter name
     * is not found, an Exception will be thrown.
     */
    public static String[] getArray(String str, String splitstr) {
        if (str == null || str.equals("")) {
            return null;
        }
        String[] result = str.split(splitstr);
        return result;
    }

    public static String generator() {
        StringBuffer now = new StringBuffer(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
        int a = (int) (Math.random() * 90000.0D + 10000.0D);
        int b = (int) (Math.random() * 90000.0D + 10000.0D);
        int c = (int) (Math.random() * 90000.0D + 10000.0D);
        return (now.append(a).append(b).append(c)).toString();
    }

    /***
     * 自定义ID
     *
     * @return
     */
    public static String getCustomId() {
        StringBuffer now = new StringBuffer(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
        int a = (int) (Math.random() * 90000.0D + 10000.0D);
        return (now.append(a)).toString();
    }

    /**
     * 字符串乱码判断，并转码
     * 用getBytes(encoding)：返回字符串的一个byte数组
     * 当b[0]为  63时，应该是转码错误
     * A、不乱码的汉字字符串：
     * 1、encoding用GB2312时，每byte是负数；
     * 2、encoding用ISO8859_1时，b[i]全是63。
     * B、乱码的汉字字符串：
     * 1、encoding用ISO8859_1时，每byte也是负数；
     * 2、encoding用GB2312时，b[i]大部分是63。
     * C、英文字符串
     * 1、encoding用ISO8859_1和GB2312时，每byte都大于0；
     * <p/>
     * 总结：给定一个字符串，用getBytes("iso8859_1")
     * 1、如果b[i]有63，不用转码；  A-2
     * 2、如果b[i]全大于0，那么为英文字符串，不用转码；  B-1
     * 3、如果b[i]有小于0的，那么已经乱码，要转码。  C-1
     *
     * @param str
     * @return UTF-8格式的字符串
     */
    public static String encoding(String str) {
        if (str == null) return null;
        String retStr = str;
        byte b[];
        try {
            b = str.getBytes("ISO8859_1");
            for (int i = 0; i < b.length; i++) {
                byte b1 = b[i];
                if (b1 == 63) {
                    break;    //1
                } else if (b1 > 0) {
                    continue;//2
                } else if (b1 < 0) {        //不可能为0，0为字符串结束符
                    retStr = new String(b, "UTF-8");
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
            return retStr;
        }
        return retStr;
    }



    public static boolean isEmpty(String str) {
        return str == null || "".equals(str);
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    /**
     * 定义分割常量
     * #用于list中每个元素间的分割
     * |用于map中每一个kv对间的分割
     * =用于map中key与value间的分割
     */
    private static final String SEP1 = ",";
    private static final String SEP2 = "|";
    private static final String SEP3 = "=";

    /**
     * List转换String
     *
     * @param list
     *            :需要转换的List
     * @return String转换后的字符串
     */
    public static String ListToString(List<?> list) {
        StringBuffer sb = new StringBuffer();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i) == null || list.get(i) == "") {
                    continue;
                }
                // 如果值是list类型则调用自己
                if (list.get(i) instanceof List) {
                    sb.append(ListToString((List<?>) list.get(i)));
                    sb.append(SEP1);
                } else if (list.get(i) instanceof Map) {
                    sb.append(MapToString((Map<?, ?>) list.get(i)));
                    sb.append(SEP1);
                } else {
                    sb.append(list.get(i));
                    sb.append(SEP1);
                }
            }
        }
        return "L" + sb.toString();
    }

    /**
     * Map转换String
     *
     * @param map
     *            :需要转换的Map
     * @return String转换后的字符串
     */
    public static String MapToString(Map<?, ?> map) {
        StringBuffer sb = new StringBuffer();
        // 遍历map
        for (Object obj : map.keySet()) {
            if (obj == null) {
                continue;
            }
            Object key = obj;
            Object value = map.get(key);
            if (value instanceof List<?>) {
                sb.append(key.toString() + SEP1 + ListToString((List<?>) value));
                sb.append(SEP2);
            } else if (value instanceof Map<?, ?>) {
                sb.append(key.toString() + SEP1 + MapToString((Map<?, ?>) value));
                sb.append(SEP2);
            } else {
                sb.append(key.toString() + SEP3 + value.toString());
                sb.append(SEP2);
            }
        }
        return "M" + sb.toString();
    }

    /**
     * String转换Map
     *
     * @param mapText
     *            :需要转换的字符串
     * @return Map<?,?>
     */
    public static Map<String, Object> StringToMap(String mapText) {

        if (mapText == null || mapText.equals("")) {
            return null;
        }
        mapText = mapText.substring(1);

        Map<String, Object> map = new HashMap<String, Object>();
        String[] text = mapText.split("\\" + SEP2); // 转换为数组
        for (String str : text) {
            String[] keyText = str.split(SEP3); // 转换key与value的数组
            if (keyText.length < 1) {
                continue;
            }
            String key = keyText[0]; // key
            String value = keyText[1]; // value
            if (value.charAt(0) == 'M') {
                Map<?, ?> map1 = StringToMap(value);
                map.put(key, map1);
            } else if (value.charAt(0) == 'L') {
                List<?> list = StringToList(value);
                map.put(key, list);
            } else {
                map.put(key, value);
            }
        }
        return map;
    }

    /**
     * String转换List
     *
     * @param listText
     *            :需要转换的文本
     * @return List<?>
     */
    public static List<Object> StringToList(String listText) {
        if (listText == null || listText.equals("")) {
            return null;
        }
        listText = listText.substring(1);

        List<Object> list = new ArrayList<Object>();
        String[] text = listText.split("\\" + SEP1);
        String listStr = "";
        boolean flag = false;
        for (String str : text) {
            if (!str.equals("")) {
                if (str.charAt(0) == 'M') {
                    Map<?, ?> map = StringToMap(str);
                    list.add(map);
                } else if (str.charAt(0) == 'L' || flag) {
                    flag = true;
                    listStr += str + SEP1;
                } else {
                    list.add(str);
                }
            }
            if (str.equals("")) {
                flag = false;
                List<?> lists = StringToList(listStr);
                list.add(lists);
            }
        }
        return list;
    }

    public static Map<String, Object> jsonStrToJava(String jsonStr){
        Map<String,Object> map = new Gson().fromJson(jsonStr, new TypeToken<HashMap<String,Object>>(){}.getType());
        return map;
    }
}
